#pragma once
#include<sys/socket.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include"log.hpp"
//把套接字的各种调用接口统一包装成一个类
extern Log lg;
enum{
    SOCK_ERR=1,
    BIND_ERR,
    LISTEN_ERR
};
const int backlog=10;
class Sock
{
    public:
    Sock()
    {

    }
    ~Sock()
    {

    }
    void Socket()
    {
        //1.套接字的创建
       listen_fd= socket(AF_INET,SOCK_STREAM,0);
       if(listen_fd<0)
       {
        lg(FATAL,"Sock Creat fail!!,errno is:%d,errstring is: %s",errno,strerror(errno));
        exit(SOCK_ERR);
       }
    }
    void Bind(const uint16_t& port)
    {
        //2.准备数据
        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family=AF_INET;
        local.sin_port=htons(port);
        local.sin_addr.s_addr=INADDR_ANY;
        //3.绑定
        if(bind(listen_fd,(sockaddr*)&local,sizeof(local))<0)
        {
            lg(FATAL,"Bind fail!! errno is %d , errstring is: %s",errno,strerror(errno));
            exit(BIND_ERR);
        }
    }
    void Listen()
    {
        if(listen(listen_fd,backlog)<0)
        {
            lg(FATAL,"Listen fial!! errno is %d , errstring is: %s",errno,strerror(errno));
            exit(LISTEN_ERR);
        }
    }
    int Accept(std::string*ip,uint16_t*port)
    {
        struct sockaddr_in peer;
        socklen_t len=sizeof(peer);
        int newfd=accept(listen_fd,(sockaddr*)&peer,&len);
        if(newfd<0)
        {
            lg(WARNING,"Accept fail!!errno is %d , errstring is: %s",errno,strerror(errno));
            return -1;
        }
        *port=ntohs(peer.sin_port);
        char buffer[64];
        inet_ntop(AF_INET,&peer.sin_addr,buffer,sizeof(buffer));
        *ip=buffer;
        return newfd;
    }
    bool Connect(const std::string&ip,const uint16_t&port)
    {
        struct sockaddr_in peer;
        memset(&peer,0,sizeof(peer));
        peer.sin_family=AF_INET;
        peer.sin_port=htons(port);
        inet_pton(AF_INET,ip.c_str(),&peer.sin_addr);
        if(connect(listen_fd,(sockaddr*)&peer,sizeof(peer))<0)
        {
            //lg(FATAL,"Connect fail!! errno is %d , errstring is: %s",errno,strerror(errno));
            std::cout<<"Connect to "<<ip<<": "<<port<<"fail !!"<<std::endl;
            return false;
        }
        return true;
    }
    int Fd()
    {
        return listen_fd;
    }
    void Close()
    {
        close(listen_fd);
    }
    private:
    int listen_fd;
};